<template>
    <div class="page-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>策略列表</span>
                    <el-button type="primary" @click="openCreateDialog">创建新策略</el-button>
                </div>
            </template>
            <el-table :data="strategies" v-loading="loading" style="width: 100%">
                <el-table-column prop="id" label="ID" width="60"></el-table-column>
                <el-table-column prop="name" label="策略名称"></el-table-column>
                <el-table-column prop="type" label="类型" width="150"></el-table-column>
                <el-table-column prop="riskLevel" label="风险等级" width="100"></el-table-column>
                <el-table-column prop="status" label="状态" width="120">
                    <template #default="scope">
                        <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="rejectionReason" label="拒绝原因" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" width="280" fixed="right">
                    <template #default="scope">
                        <el-button size="small" @click="viewDetails(scope.row.id)">详情</el-button>
                        <el-button size="small" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
                        <el-button v-if="scope.row.status === 'DRAFT' || scope.row.status === 'REJECTED'" size="small"
                            type="success" @click="handleSubmitForReview(scope.row)">提交审核</el-button>
                        <el-button size="small" type="info" @click="openAdjustmentDialog(scope.row)">调仓</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <StrategyForm v-model:visible="formDialogVisible" :strategy-data="selectedStrategy"
            @saved="handleSaveStrategy" />

        <AdjustmentDialog v-model:visible="adjustmentDialogVisible" :strategy-id="selectedStrategyForAdjustment?.id"
            :initial-components="selectedStrategyForAdjustment?.components" @adjusted="fetchStrategies" />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getAllStrategies, createStrategy, updateStrategy, submitForReview } from '@/api/strategyApi';
import StrategyForm from '@/components/strategies/StrategyForm.vue';
import AdjustmentDialog from '@/components/strategies/AdjustmentDialog.vue';

const router = useRouter();
const strategies = ref([]);
const loading = ref(true);
const formDialogVisible = ref(false);
const adjustmentDialogVisible = ref(false);
const selectedStrategy = ref(null);
const selectedStrategyForAdjustment = ref(null);

const fetchStrategies = async () => {
    loading.value = true;
    try {
        const response = await getAllStrategies();
        strategies.value = response.data;
    } catch (error) {
        ElMessage.error('获取策略列表失败');
    } finally {
        loading.value = false;
    }
};

const getStatusTagType = (status) => {
    switch (status) {
        case 'DRAFT': return 'info';
        case 'UNDER_REVIEW': return '';
        case 'ACTIVE': return 'success';
        case 'REJECTED': return 'danger';
        case 'INACTIVE': return 'warning';
        default: return 'info';
    }
}

const openCreateDialog = () => {
    selectedStrategy.value = null;
    formDialogVisible.value = true;
};

const openEditDialog = (strategy) => {
    selectedStrategy.value = strategy;
    formDialogVisible.value = true;
};

const handleSaveStrategy = async (data, isEdit) => {
    try {
        if (isEdit) {
            // 注意: 此处依然调用旧的更新接口，它可能只更新部分元数据
            await updateStrategy(data.id, data);
            ElMessage.success('策略更新成功');
        } else {
            await createStrategy(data);
            ElMessage.success('策略创建成功');
        }
        formDialogVisible.value = false;
        fetchStrategies();
    } catch (error) {
        const errorMessage = error.response?.data?.message || error.message;
        ElMessage.error(`保存失败: ${errorMessage}`);
    }
};

const viewDetails = (id) => {
    router.push(`/strategies/${id}`);
}

const handleSubmitForReview = async (strategy) => {
    try {
        await submitForReview(strategy.id);
        ElMessage.success(`策略 "${strategy.name}" 已成功提交审核`);
        fetchStrategies();
    } catch (error) {
        const errorMessage = error.response?.data?.message || error.message;
        ElMessage.error(`提交审核失败: ${errorMessage}`);
    }
};

const openAdjustmentDialog = (strategy) => {
    selectedStrategyForAdjustment.value = strategy;
    adjustmentDialogVisible.value = true;
}

onMounted(fetchStrategies);
</script>

<style scoped>
.page-container {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>